<template>
	<view class="wrap" style="100vh">
		<js-error mode="bottom" ref="jsError"></js-error>
		<u-sticky class="u-sticky">
			<view class="cu-bar search" style="padding: 10px">
			  <u-search
			    v-model="barCode"
			    ref="uSearch"
			    :focus="focus"
			    placeholder="请先聚焦后扫描"
			    :show-action="false"
			    @search="confirm"
			  ></u-search>
			  <view style="margin-left: 10px; display: flex; flex-direction: column">
			    <u-icon @click="search" name="scan" size="50"></u-icon>
			  </view>
			</view>
		</u-sticky>
		<!-- -->
		<view v-if="flag">
			<!-- style="padding: 0 10px" -->
			<u-form :model="model" :rules="rules" ref="uForm" label-position="left" >
				<scroll-view
				  scroll-y="true"
				  :style="{ height: scrollViewHeight + 'px' }"
				  class="scroll-view-class"
				>
				<!-- class="bg-white  radius" -->
					<view class="bg-white  padding  margin-bottom shadow">
						<u-form-item label="存货代码"  label-width="180">
							{{ model.basInv.cinvaddcode }}
						</u-form-item>
						<u-form-item label="存货编码"  label-width="180">
							{{ model.basInv.cinvcode }}
						</u-form-item>
						<u-form-item label="存货名称" prop="gongxu_name" label-width="180">
							{{ model.basInv.cinvname }}
						</u-form-item>
						
						<u-form-item label="加工数量" prop="gongxu_name" label-width="180">
							<!-- {{ model.iqty }}	 -->
							<u-input placeholder="请输入" v-model="model.iqty" type="digit" di maxlength="64" @blur="confirmIqtyModal" :clearable="false"></u-input>
						</u-form-item>
						<u-form-item label="生产线" prop="cline" label-width="180">
							<!-- {{ model.iqty }}	 -->
							<u-input placeholder=" " v-model="model.cline" type="text" maxlength="64" :clearable="false" ></u-input>
						</u-form-item>
						
						
						<!-- <u-form-item label="开始时间" prop="stratDate" label-width="180">
							<picker mode="multiSelector" :value="multiIndexStart" :range="multiRangeStart"   @change="onMultiChangeStart">
							  <view class="picker">
									<template v-if="formattedDateTimeStart && showDataStart">
										 {{ formattedDateTimeStart }}
									</template>
									<template v-else>
										<view class="select-date-prompt">请选择开始日期</view>
										
									</template>
							  </view>
							</picker>	
						</u-form-item> -->
						<u-form-item label="加工日期" prop="endDate" label-width="180">
							<!-- :value="model.endDate ? model.endDate : ''" start="2015-09-01 00:00" @change="DateChange('endDate', $event)" -->
							<picker  mode="multiSelector" :value="multiIndexEnd" :range="multiRangeEnd"   @change="onMultiChangeEnd">
							  <view class="picker">
							    <!-- {{ model.repairDate ? model.repairDate : "请选择维修日期" }} -->
									<template v-if="formattedDateTimeEnd && showDataEnd">
										{{ formattedDateTimeEnd }}
										<!-- {{ model.endDate }} -->
									</template>
									<template v-else>
										<view class="select-date-prompt">请选择加工日期</view>
									</template>
							  </view>
							</picker>	
						</u-form-item>
						
						<view class="flex margin-top">
							<u-icon class="cuIcon-titles" size="50" color="#0081ff"></u-icon> 
							<view class="text-xxl text-black">工装信息</view>
						</view>
						
					</view>
					<view class="bg-white margin" v-for="(item,index) in model.moldList" :key="index">
						<view  class="cu-form-group flex justify-between ">
							<view class="flex align-center">
								<view style="display: inline-block;padding: 5px;background: #3E97B0;color: #fff;min-width: 40px;text-align: center;font-style: italic;font-weight: bold">
									{{ index + 1  }}
								</view>
								<view class="text-xxl margin-left text-black">
									{{ item.basMold&&item.basMold.code ? item.basMold.code : '' }}
								</view>
							</view>
							<!--  -->
							<view>
								<text style="font-size: 35px;" class="cuIcon-deletefill text-sl text-red" @tap="delMoldNum(item,index)" v-if="model.moldList.length > 1"></text>
							</view>
						</view>
						<u-form-item label="名称"  label-width="220" class="paddingForm">
							 {{ item.basMold&&item.basMold.name ? item.basMold.name : '' }}
						</u-form-item>
						<u-form-item label="类型"  label-width="220" class="paddingForm">
							{{ item.basMold&&item.basMold.basMoldCls&&item.basMold.basMoldCls.code ? '('+item.basMold.basMoldCls.code+')' : '' }}
							 {{ item.basMold&&item.basMold.basMoldCls&&item.basMold.basMoldCls.name ? item.basMold.basMoldCls.name : '' }}
						</u-form-item>
						<u-form-item label="工序"  label-width="220" class="paddingForm">
							 {{ item.operCode ? item.operCode : '' }}
						</u-form-item>
						<u-form-item label="设备名称" prop="devName" label-width="220" class="paddingForm">
							<u-input placeholder="请输入" v-model="item.devName" type="text" maxlength="64"></u-input>	
						</u-form-item>
						<u-form-item label="工装尾号" prop="lastNum" label-width="220" class="paddingForm" :label-position="item.lastNums.length>1 ? 'bottom' : 'left'" >
							<js-radio v-model="item.lastNum" :items="item.lastNums" v-if="item.lastNums.length>1 && !model.cline.includes(vuex_config.cline)"></js-radio>	
							<js-checkbox v-model="item.lastNum" :itemsList="item.lastNums" v-if="item.lastNums.length>1 && model.cline.includes(vuex_config.cline)"></js-checkbox>
							<u-input placeholder=" " v-model="item.lastNum" type="text" maxlength="64" :disabled="true"  v-else></u-input>
						</u-form-item>
					</view>				
				</scroll-view>
				
				
				
			</u-form>
			<view class="cu-bar"></view>
			<view class="form-footer cu-bar foot" v-if="submitStatus">
				<u-button class="btn" type="primary" @click="submit">提交</u-button>
			</view>
			
		</view>
		<u-empty  style="height: 80vh;" text="请扫码现品票"  v-if="!flag"></u-empty>
		
		<view>
			<movable-area class="movable-area1">
				<movable-view class="movable-view" :x="x" :y="y" direction="all">
					<view @click="handleSearch" class="custom-style" style="width: 90px; height: 70px; color: #fff; border-radius: 10rpx;">
						<view style="font-size: 16px;display: flex; flex-direction: column;text-align: center;">
							<text class="cuIcon-scan text-xxls text-blue"></text>
							<view class="text-blue">现品票识别</view>
						</view>
					</view>
					
				</movable-view>
			</movable-area>
		</view>
		<u-modal v-model="smshow" title="确认修改数量" @confirm="confirmConfirmIqty" :show-cancel-button="true" width="80%">
			<view class="slot-content">
				<view class="cu-bar" style="padding: 10px">
					<u-input placeholder="请输入修改数量" type="number" v-model="confirmIqty" maxlength="64"></u-input>
				</view>
			</view>
		</u-modal>
	</view>
</template>

<script>
	import moment from 'moment'
	export default {
		data() {
			const now = new Date();
			return {
				model: {
					iqty:0,
					lastNum:''
				},
				confirmIqty:'',
				smshow:false,
				focus:false,
				barCode: "",
				lastNum: '',
				rules: {
					lastNum:[
						{
							required: true,
							message: '请选择工装尾号',
							trigger: ['change','blur'],
						}
					]
				},
				barcode1:'',
				scrollViewHeight:0,
				formFooterHeight: 0,
				headerHeight: 0,
				x: 650, //x坐标
				y: 650, //y坐标
				flag:false,
				showDataStart:false,
				showDataEnd:false,
				multiIndexStart: [
					now.getFullYear() - 1900, // 年份
					now.getMonth(),           // 月份 (0-11)
					now.getDate() - 1,        // 日期 (1-31，减1以用于索引)
					now.getHours(),           // 小时 (0-23)
				],
				multiRangeStart: this.getMultiRange(),
				multiIndexEnd: [
					now.getFullYear() - 1900, // 年份
					now.getMonth(),           // 月份 (0-11)
					now.getDate() - 1,        // 日期 (1-31，减1以用于索引)
					now.getHours(),           // 小时 (0-23)
				],
				multiRangeEnd: this.getMultiRange(),
				submitStatus:false,
				
			}
		},
		computed: {
			formattedDateTimeStart() {
			  const year = this.multiRangeStart[0][this.multiIndexStart[0]];
			  const month = String(this.multiRangeStart[1][this.multiIndexStart[1]]).padStart(2, '0');
			  const day = String(this.multiRangeStart[2][this.multiIndexStart[2]]).padStart(2, '0');
			  const hour = String(this.multiRangeStart[3][this.multiIndexStart[3]]).padStart(2, '0');
			  this.model.stratDate = `${year}-${month}-${day} ${hour}:00:00`
			  return `${year}-${month}-${day} ${hour}`;
			},
			formattedDateTimeEnd() {
			  const year = this.multiRangeEnd[0][this.multiIndexEnd[0]];
			  const month = String(this.multiRangeEnd[1][this.multiIndexEnd[1]]).padStart(2, '0');
			  const day = String(this.multiRangeEnd[2][this.multiIndexEnd[2]]).padStart(2, '0');
			  const hour = String(this.multiRangeEnd[3][this.multiIndexEnd[3]]).padStart(2, '0');		  
			  this.model.endDate = `${year}-${month}-${day} ${hour}:00:00`
			  return `${year}-${month}-${day} ${hour}`;
			}
		},
		// 计算每一个item的模具尾号
		onReady() {
			
			
		},
		mounted() {
			
			
		  this.calculateScrollViewHeight();
		},
		methods:{
			// 将可能包含 HTML 的提示文案标准化为 showModal 可换行的纯文本
			formatModalContent(msg){
				if(!msg) return '';
				let s = String(msg);
				// 处理服务端常见换行标记
				s = s.replace(/<br\s*\/?>/gi, '\n');
				s = s.replace(/<\/p>\s*<p>/gi, '\n');
				s = s.replace(/<\/?p[^>]*>/gi, '');
				// 处理各种换行与制表符
				s = s.replace(/\r\n|\r|\n/g, '\n');
				s = s.replace(/\r\t/g, '\n'); // 兼容后端返回的 \r\t
				s = s.replace(/\/r\/t/gi, '\n'); // 兼容写成 /r/t 的字符串
				s = s.replace(/\t+/g, ' ');
				// 处理常见空白实体
				s = s.replace(/&nbsp;/gi, ' ');
				// 压缩多余空格并去除首尾
				s = s.replace(/[ ]{2,}/g, ' ').trim();
				return s;
			},
			confirmConfirmIqty(){
				if(this.model.iqty!= this.confirmIqty){
					this.model.iqty = this.model.iqtySave
					this.confirmIqty = ''
					this.$refs.jsError.showError('', '修改失败，两次数量不一致' , 'error');

				}
			},
			confirmIqtyModal(){
				this.smshow = true
			},
			getMultiRange() {
			  let yearRange = [];
			  let monthRange = [];
			  let dayRange = [];
			  let hourRange = [];
			  let minuteRange = [];
			  let secondRange = [];
			  
			  // 生成年月日时分秒的数组
			  for (let i = 1900; i <= 2100; i++) yearRange.push(i);
			  for (let i = 1; i <= 12; i++) monthRange.push(i);
			  for (let i = 1; i <= 31; i++) dayRange.push(i);
			  for (let i = 0; i <= 23; i++) hourRange.push(i);
			  for (let i = 0; i <= 59; i++) minuteRange.push(i);
			  for (let i = 0; i <= 59; i++) secondRange.push(i);
			  
			  // return [yearRange, monthRange, dayRange, hourRange, minuteRange, secondRange];
			  return [yearRange, monthRange, dayRange, hourRange]
			},
			onMultiChangeStart(e) {
				console.log(e,this.formattedDateTime)
			  this.multiIndexStart = e.detail.value;
			  this.showDataStart = true;
			},
			onMultiChangeEnd(e) {
				console.log(e,this.formattedDateTime)
			  this.multiIndexEnd = e.detail.value;
			  this.showDataEnd = true;
			},
			
			DateChange(item, e) {
			  console.log(item, e);
			  //   this.date = e.detail.value;
			  if (item === "stratDate") {
			    this.model.stratDate = e.detail.value;
			  } else if(item === "endDate"){
				this.model.endDate = e.detail.value;
			  }
			  this.$forceUpdate();
			},
			handleSearch(){
				if(this.vuex_config.deviceType === this.vuex_config.deviceTypeAPP){
					this.search()
				}else if(this.vuex_config.deviceType === this.vuex_config.deviceTypePDA){
					this.handleFocus()
				}
			},
			submit(){
				// 遍历 this.model.moldList
				let hasError = false;
				let hasErrorMsg = ''
				this.model.moldList.some((item,index) => {
					// 把item.basMold 去掉 basMold这个对象，把里面的值平铺
					// item = {...item,...item.basMold}
					// item.lastNums.length>1
				  item.devName  = item.devName ? item.devName.toUpperCase() : ''
				  if (item.lastNums.length>1 && !item.lastNum) {
				    hasErrorMsg = `工装编号"${item.basMold.code}"名称"${item.basMold.name}"请选择工装尾号`
				    hasError = true; // 设置错误标志
				    return true; // 中断 some 遍历
				  }
				  return false;
				});		
				if (hasError) {
				  this.$refs.jsError.showError('', hasErrorMsg , 'error');
				  return false;
				}
				this.model.barcode = this.barcode1
				// 转大写
				this.model.devName = this.model.devName ? this.model.devName.toUpperCase() : ''
				const data = this.model
				this.$u.api.asd.saveBatch(data).then((res)=>{
					if(res.result == "true"){
						this.$u.toast(res.message)
						this.flag = false
						this.model = {}
					}else{
						this.$refs.jsError.showError('', res.message , 'error');
					}
				})
				
			},
			delMoldNum(item,index) {
				// 
				const that = this;
				uni.showModal({
					title: '删除',
					content: '确认是否删除？',
					confirmColor: '#00007f',
					success: (res) => {
						if (!res.confirm) {
							return false;
						} else {
							this.model.moldList.splice(index,1)
						}
					}
				})
			},
			async calculateScrollViewHeight() {
			  	await this.$nextTick(); // 确保DOM更新完成
			  	const query = uni.createSelectorQuery().in(this);
				// 获取form-footer 的高度
				query.select(".form-footer").boundingClientRect((rect) => {
					if (rect && rect.height > 0) { // 确保rect有效且高度大于0
						this.formFooterHeight = rect.height;
					}
				});
				query.select(".u-sticky").boundingClientRect((rect) => {
					if (rect && rect.height > 0) { // 确保rect有效且高度大于0
					this.headerHeight = rect.height;
					// 获取屏幕高度
					const systemInfo = uni.getSystemInfoSync();
					const screenHeight = systemInfo.windowHeight;
					// 计算scroll-view高度
					this.scrollViewHeight = screenHeight - this.headerHeight - this.formFooterHeight -80;
					console.log(this.scrollViewHeight, 'this.scrollViewHeight');
					} else {
					console.error('无法获取.u-sticky的高度或高度为0');
					}
				}).exec();
			},
			handleFocus() {
			  var _that = this;
			  _that.focus = false;
			  setTimeout(() => {
			    _that.focus = true;
			  }, 500);
			},
			confirm() {
				this.focus = false
				console.log(this.barCode, 'barCode')
				this.barcode1 = this.barCode
				this.commonSearch(this.barCode)
			},
			search() {
				var _that = this;
				_that.focus = false				
				// const scanner = uni.requireNativePlugin('Ba-Scanner')
				// if(scanner === undefined){
				// 	uni.scanCode({
				// 		scanType: ["barCode", "qrCode"],
				// 		// onlyFromCamera: true,
				// 		success: async (res) => {
				// 			that.barCode = res.result;
				// 			await that.commonSearch(res.result)
				// 		},
				// 	});
				// }else{
				// 	scanner.onScan({
				// 			hintText: '',
				// 			isShowToast: false,
				// 			barcodeFormats: ["QR Code","Codabar"]
				// 		},
				// 		async (ret) => {
				// 			console.log('ret',ret)
				// 			if (ret.result) {
				// 				await that.commonSearch(ret.result)
				// 			}
				// 		});
				// }
				
				var mpaasScanModule = uni.requireNativePlugin("Mpaas-Scan-Module");
				mpaasScanModule.mpaasScan({
					// 扫码识别类型，参数可多选，qrCode、barCode，不设置，默认识别所有
					'scanType':  ['qrCode','barCode'],
					// 是否隐藏相册，默认false不隐藏
					'hideAlbum': false,
					//ios需要设置这个参数，只支持中英文 zh-Hans、en，默认中文                       
					'language' : 'en',
					//相册选择照片识别错误提示(ios)
					'failedMsg': '未识别到二维码，请重试',
					//Android支持全屏需要设置此参数
					'screenType': 'full'              
				},
				async (ret) => {
					console.log('ret',ret)
					if(ret.resp_message == 'success'){
						_that.barCode = ret.resp_result;
						await _that.commonSearch(ret.resp_result)
					}
				})
				
			},
			async commonSearch(barCode) {
				let that = this
				//扫货位
				this.$u.api.asd.findMolds({
					barCode,
				}).then(res => {
					if (res.result == 'true') {

						// 弹出一个模态框 内容为res.msg, 按换行展示
						if(res.msg){
							const formatted = this.formatModalContent(res.msg);
							uni.showModal({
								title: '提示',
								content: formatted,
								showCancel: true,
								success: function (resSuccess) {
									console.log('success',resSuccess,resSuccess.confirm)
									if (resSuccess.confirm ) {
										that.submitStatus = true
									}
								}
							})
						} else { 
							that.submitStatus = true
						}

						console.log(res.list,'res.list===', that.submitStatus)
						
						// 返回一个新的数组，res.list数组里面 lastNums的数组长度大于1，设置lastNum 为''，把basMold 里面的值平铺，并且lastNums的数组长度大于1，设置lastNum 为''
						let newList = res.list.map(item=>{
							item = {...item,...item.basMold}
							console.log(item,'----')
							
							if(item.lastNums.length>1){
								item.lastNum = ''
								item.basMold.lastNum = ''

								// 移除item.lastNum 数组里面的每一项的checked属性
								
								
							}
							return item
						})

						this.flag = true

						if(!this.model.iqty) {
							this.model = {
								...this.model,
								cline: res.xppData.cline,
								devName: res.xppData.devName,
								iqty : res.xppData.qty,
								iqtySave : res.xppData.qty,
								basInv : res.xppData.basInv,
								moldList : newList
							}
						}else{
							if(this.model.basInv&&this.model.basInv.cinvcode && this.model.basInv.cinvcode === res.xppData.basInv.cinvcode){
								this.model.iqty = this.model.iqty + res.xppData.qty
								this.model.iqtySave = this.model.iqty + res.xppData.qty
								this.model = {
									...this.model,
									basInv : res.xppData.basInv,
									moldList : newList,
									cline: res.xppData.cline,
								}
							}else if(this.model.basInv&&this.model.basInv.cinvcode && this.model.basInv.cinvcode != res.xppData.basInv.cinvcode){
								uni.showModal({
									title: '提示',
									content: '是否更换存货',
									showCancel: true,
									success: function (resSuccess) {
										console.log('success',resSuccess,resSuccess.confirm)
										if (resSuccess.confirm ) {
											this.model = {
												basInv : res.xppData.basInv,
												iqty : res.xppData.qty,
												iqtySave: res.xppData.qty,
												moldList : newList,
												cline: res.xppData.cline,
											}	
											this.$forceUpdate()
											console.log('model====',this.model)
										}
									}.bind(this)
								});
							}
						}
						
						if(this.model.moldList.lastNums.length>1){
							// 遍历 this.model.moldList
							this.model.moldList.forEach(item=>{
								item.lastNums.forEach(itemChild=>{
									delete itemChild.checked
								})
							})
						}

						console.log('model',this.model)
						setTimeout(()=>{
							that.makeSound("cg");
						},500)
						// that.$u.toast('成功！');
					} else {
						setTimeout(()=>{
							that.makeSound("sb");
						},500)
						that.$refs.jsError.showError('', res.message, 'error');
					}
					setTimeout(() => {
						this.barCode = '';
					}, 500);
					if(this.vuex_config.deviceType === this.vuex_config.deviceTypePDA){
						this.handleFocus()
					}
							
				})
			
				setTimeout(() => {
					this.barCode = '';
				}, 500);
			
			},
			makeSound(name){
				console.log("=====testClick=====");
				let src = '/static/'+name+'.mp3';
				//实例化声音  
				const Audio = uni.createInnerAudioContext();
				Audio.autoplay = true;
				Audio.src = src; //音频地址  
				Audio.play(); //执行播放  
				Audio.onError((res) => {
				});
				Audio.onPause(function() {
					console.log('end');
					Audio.destroy();
				});
			},
			
		}
	}
</script>

<style  lang="scss">
	$all_width: 96rpx;
	$all_height: 96rpx;
	.movable-area1 {
	  z-index: 999;
	  height: 97vh;
	  width: 650rpx;
	  position: fixed;
	  right: $all_width;
	  top: -($all_height + 70rpx);
	  pointer-events: none; //此处要加，鼠标事件可以渗透
	
	  .movable-view {
	    width: $all_width;
	    height: $all_height;
	    pointer-events: auto; //恢复鼠标事件
	
	    image {
	      width: $all_width;
	      height: $all_height;
	    }
	  }
	}
	.cuIcon-titles{
		color:#0081ff;
		font-size: 50rpx;
	}
	.paddingForm{
		padding: 18rpx 28rpx;
	}
	.text-xxls{
		font-size: 60rpx;
	}
	.select-date-prompt{
		font-size: 28rpx;
		color: #dfdfdf !important;
	}
	.cu-bar.foot{
		z-index: 100;
	}
	.form-footer{
		margin: 0;
	}
	.picker {
	  padding: 10px;
	  background-color: #fff;
	  text-align: center;
	}
</style>